import React, { createContext, useState, useReducer, useEffect } from 'react';
import Taro from '@tarojs/taro';
import { createReducerMapper, useMyReducer } from '@/utils/index';
import { CollectionList_Web } from '@/pages/_server/_class/MyCollection/CollectionList';
import { apiGetCollectionList } from '@/pages/_server/_api/ApiCollection/apiGetCollectionList';
export type CollectionContextType = {
    collectionExhibitionState: CollectionExhibition;
};

export const CollectionContext = createContext<CollectionContextType>(undefined);

/** 页面渲染的列表 */
export type CollectionExhibition = {
    collectionList: CollectionList_Web[];
};

/** 处理reducer的函数 */
const handleMapper = createReducerMapper({
    initializer: null as CollectionExhibition,
    handleMapper: {
        /** 刷新列表 */
        freshList: (state, payload?: { collectionList: CollectionList_Web[] }) => {
            let list = [...payload.collectionList];
            let newState: Pick<CollectionExhibition, 'collectionList'> = {
                collectionList: [],
            };
            newState.collectionList = [...list];
            return { ...state, ...newState };
        },
        /** 修改当前收藏状态*/
        setLikes: (state, payload:{id:string,setLike:string})=>{
            state.collectionList.forEach(item=>{
                if(item.id === payload.id){
                    item.likes = payload.setLike                    
                }
            })
            return {...state}
        }
    },
});

const initialState: CollectionExhibition = {
    collectionList: [],
};

/** 使用需要展示的列表 */
export const useCollectionExhibitionList = () => {
    const [CollectionExhibitionState, CollectionExhibitionDispatch] = useMyReducer({
        initializer: initialState,
        handleMapper,
    });
    const [loadingStatus, setLoadingStatus] = useState<'Loading' | 'complete'>('Loading');
    useEffect(() => {
        // 页面加载完成时初始化列表
        apiGetCollectionList().then((res) => {
            if (!res) return;
            CollectionExhibitionDispatch({
                type: 'freshList',
                payload: {
                    collectionList: res.data,
                },
            });
            setLoadingStatus('complete');
        });
    }, [CollectionExhibitionDispatch]);

    return {
        CollectionExhibitionState,
        CollectionExhibitionDispatch,
        loadingStatus
    };
};

